import socket
import os
import hashlib

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind(("localhost",6969))  #绑定监听端口

server.listen(5)  #监听

print("[*]Server正在监听......")

while True:
    conn,addr = server.accept() #等待连接
    print("[+]服务端已连接......")
    print("[+]conn:",conn,"\naddr:",addr)
    while True:
        agent_response = conn.recv(1024)
        file_size = int(agent_response.decode("utf-8"))
        print("接收到的大小：",file_size)

        conn.send("准备好接收".encode("utf-8"))  #确认接收

        agent_response = conn.recv(1024)
        log_type = str(agent_response.decode("utf-8"))
        conn.send("准备好接收".encode("utf-8"))  # 确认接收

        agent_response = conn.recv(1024)
        file_name = str(agent_response.decode("utf-8"))

        if log_type == "Linuxcmd":
            f = open("Linuxcmd"+file_name,"wb")
        elif log_type == "Windowscmd":
            f = open("Windowscmd" + file_name, "wb")
        elif log_type == "Webcmd":
            f = open("webcmd" + file_name, "wb")
        elif log_type == "pcapcmd":
            f = open("pcapcmd" + file_name, "wb")
        else:
            f = open("new" + file_name, "wb")
        conn.send("准备好接收".encode("utf-8"))  # 确认接收

        received_size = 0

        while received_size < file_size:
            size = 0
            if file_size - received_size > 1024:
                size = 1024
            else:
                size = file_size-received_size  #最后一次接收

            data = conn.recv(size)  #多次接收
            data_len = len(data)
            received_size += data_len
            print("已接收：",int(received_size/file_size*100),"%")

            f.write(data)

        f.close()
        print("实际接收的大小:", received_size)  # 解码

conn.close()







